package com.changeover.gwt.connection.dispatcher.server;

import java.text.MessageFormat;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import net.customware.gwt.dispatch.client.standard.StandardDispatchService;
import net.customware.gwt.dispatch.server.Dispatch;
import net.customware.gwt.dispatch.server.SimpleDispatch;
import net.customware.gwt.dispatch.shared.Action;
import net.customware.gwt.dispatch.shared.DispatchException;
import net.customware.gwt.dispatch.shared.Result;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Dispatch Servlet
 * 
 * @author Roman Kostenko
 */
@SuppressWarnings("serial")
public class DispatchServlet extends RemoteServiceServlet implements StandardDispatchService {

    private Dispatch dispatch;

    @Override
    public void init() throws ServletException {
        super.init();
        // get Handler Registry which has been made by Spring
        ServletConfig config = getServletConfig();
        IHandlerRegistry registry = (IHandlerRegistry) config.getServletContext().getAttribute("handlerRegistry");
        
        // register server handlers
        dispatch = new SimpleDispatch(registry.getRegistry());
    }

    public Result execute(Action<?> action) throws DispatchException {
        try {
            return dispatch.execute(action);
        } catch (RuntimeException e) {
            log(MessageFormat.format("Exception while executing {0}: {1}", action.getClass().getName(),e.getMessage()), e);
            throw e;
        }
    }

}
